package com.yhwch.fun.utils;

import com.yhwch.fun.domain.SplitPair;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SplitUtil {

    /**
     * 将区间值平均分割为n个小区间
     * @param shardKeyBegin 起始值
     * @param shardKeyEnd 结束值
     * @param segmentCount 分割块数
     * @return 每块的大小
     */
    public static List<Integer> computeTableShardInterval(int shardKeyBegin, int shardKeyEnd, int segmentCount){
        int shardKeyCounts = shardKeyEnd - shardKeyBegin;
        if(shardKeyCounts < 1){
            return Collections.emptyList();
        }
        int intervalSize ;
        List<Integer> back = new ArrayList<>();
        for(int i = 0; i < segmentCount; i++){
            if(shardKeyCounts%(segmentCount-i) == 0){
                intervalSize = shardKeyCounts/(segmentCount-i);
                //余量递减
                shardKeyCounts = shardKeyCounts - intervalSize;
            }else{
                intervalSize = (shardKeyCounts/(segmentCount-i) +1);
                shardKeyCounts = shardKeyCounts - intervalSize;
            }
            // 区间为0的时候表示已分完，无法再分割
            if(intervalSize == 0){
                break;
            }
            back.add(intervalSize);
        }
        return back;
    }

    /**
     * 返回区间的[开始值,结束值),左闭右开模式
     * 如 0~10 分隔三份（注意：最后区间中不包含10）
     * SplitPair(begin=0, end=4)
     * SplitPair(begin=4, end=7)
     * SplitPair(begin=7, end=10)
     * @param shardKeyBegin
     * @param shardKeyEnd
     * @param segmentCount
     * @return
     */
    public static List<SplitPair> computeTableShardIntervalPair(int shardKeyBegin, int shardKeyEnd, int segmentCount){
        List<Integer> list = computeTableShardInterval(shardKeyBegin,shardKeyEnd,segmentCount);
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        List<SplitPair> back = new ArrayList<>();
        int begin = 0;
        int end = 0;
        for (int i = 0; i < list.size() ; i++) {
            if(i==0){
                end += list.get(i);
            }else{
                begin += list.get(i-1);
                end += list.get(i);
            }
            back.add(new SplitPair(begin,end));
        }
        return back;
    }


    public static void main(String[] args) {
       List<SplitPair> list = computeTableShardIntervalPair(0,10,3);
        for (int i = 0; i < list.size() ; i++) {
            System.out.println(list.get(i));
        }
    }
}
